package com.ssy.lingxi.logistics.serviceimpl;

import cn.hutool.core.util.StrUtil;
import com.ssy.lingxi.common.model.dto.UserLoginCacheDTO;
import com.ssy.lingxi.common.model.vo.PageVO;
import com.ssy.lingxi.common.response.PageData;
import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.logistics.entity.ReceiverAddress;
import com.ssy.lingxi.logistics.model.enums.CommonBooleanEnum;
import com.ssy.lingxi.logistics.model.enums.ReceiverAddressCreateTypeEnum;
import com.ssy.lingxi.logistics.model.response.mobile.MobileReceiverAddressListResponse;
import com.ssy.lingxi.logistics.repository.ReceiverAddressRepository;
import com.ssy.lingxi.logistics.service.IMobileReceiverAddressService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * app收货地址服务实现类
 * @author yzc
 * @version 2.0.0
 * @date 2020/7/13
 */
@Service
public class MobileReceiverAddressServiceImpl implements IMobileReceiverAddressService {

    @Resource
    private ReceiverAddressRepository receiverAddressRepository;

    @Override
    public Wrapper<PageData<MobileReceiverAddressListResponse>> pageReceiverAddress(PageVO request, UserLoginCacheDTO loginUser) {
        Pageable page = PageRequest.of(request.getCurrent() - 1, request.getPageSize(), Sort.by("id").ascending());

        Specification<ReceiverAddress> specification = buildSpecification(loginUser.getMemberId(), loginUser.getMemberRoleId());
        Page<ReceiverAddress> pageList = receiverAddressRepository.findAll(specification, page);

        // 组装数据
        List<MobileReceiverAddressListResponse> resultList = convertAddressResponse(pageList.getContent());

        return Wrapper.success(new PageData<>(pageList.getTotalElements(), resultList));
    }

    @Override
    public Wrapper<List<MobileReceiverAddressListResponse>> listReceiverAddressDefault(UserLoginCacheDTO loginUser) {
        Sort sort = Sort.by("createTime").descending();
        Specification<ReceiverAddress> specification = buildSpecification(loginUser.getMemberId(), loginUser.getMemberRoleId());
        List<ReceiverAddress> receiverAddressList = receiverAddressRepository.findAll(specification, sort);

        // 默认地址首位
        List<ReceiverAddress> handleList = new ArrayList<>();
        Iterator<ReceiverAddress> iterator = receiverAddressList.iterator();
        while (iterator.hasNext()) {
            ReceiverAddress next = iterator.next();
            if (CommonBooleanEnum.YES.getCode().equals(next.getIsDefault())) {
                handleList.add(next);
                iterator.remove();
                break;
            }
        }
        handleList.addAll(receiverAddressList);

        // 组装数据
        List<MobileReceiverAddressListResponse> resultList = convertAddressResponse(handleList);

        return Wrapper.success(resultList);
    }

    private Specification<ReceiverAddress> buildSpecification(Long memberId, Long roleId) {
        return ((Specification<ReceiverAddress>) (root, query, cb) -> {
            List<Predicate> predicateList = new ArrayList<>();
            predicateList.add(cb.equal(root.get("memberId"), memberId));
            predicateList.add(cb.equal(root.get("roleId"), roleId));
            predicateList.add(cb.equal(root.get("createType"), ReceiverAddressCreateTypeEnum.LOGISTICS.getCode()));

            Predicate[] p = new Predicate[predicateList.size()];
            return query.where(predicateList.toArray(p)).getRestriction();
        });
    }

    private List<MobileReceiverAddressListResponse> convertAddressResponse(List<ReceiverAddress> receiverAddressList) {
        return receiverAddressList.stream().map(e -> {
            MobileReceiverAddressListResponse receiverAddressListResponse = new MobileReceiverAddressListResponse();
            receiverAddressListResponse.setId(e.getId());
            receiverAddressListResponse.setReceiverName(e.getReceiverName());
            receiverAddressListResponse.setProvinceCode(e.getProvinceCode());
            receiverAddressListResponse.setProvinceName(e.getProvinceName());
            receiverAddressListResponse.setCityCode(e.getCityCode());
            receiverAddressListResponse.setCityName(e.getCityName());
            receiverAddressListResponse.setDistrictCode(e.getDistrictCode());
            receiverAddressListResponse.setDistrictName(e.getDistrictName());
            receiverAddressListResponse.setStreetCode(StrUtil.isEmpty(e.getStreetCode()) ? "" : e.getStreetCode());
            receiverAddressListResponse.setStreetName(StrUtil.isEmpty(e.getStreetName()) ? "" : e.getStreetName());
            receiverAddressListResponse.setAddress(e.getAddress());
            receiverAddressListResponse.setPostalCode(e.getPostalCode());
            receiverAddressListResponse.setPhone(e.getPhone());
            receiverAddressListResponse.setTel(e.getTel());
            receiverAddressListResponse.setIsDefault(e.getIsDefault());
            return receiverAddressListResponse;
        }).collect(Collectors.toList());
    }

}